package com.sen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sen.dto.ResourceDTO;
import com.sen.entity.Resource;
import com.sen.mapper.ResourceMapper;
import com.sen.result.Result;
import com.sen.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  资源服务实现类
 * </p>
 *
 * @author sen
 * @since 2021-03-29
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 新增一个资源信息
     * @param resource
     * @return
     */
    @Override
    public Result saveResource(Resource resource) {
        boolean b = this.save(resource);
        if (b){
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    /**
     * 根据资源id删除相应的资源记录
     * @param id
     * @return
     */
    @Override
    public Result deleteResourceById(Integer id) {
        // 删除资源表中的记录
        boolean b = this.removeById(id);
        // 删除角色资源表中的记录
        resourceMapper.deleteRoleResourceById(id);
        if (b){
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    /**
     * 更新资源信息
     * @param resource
     * @return
     */
    @Override
    public Result updateResource(Resource resource) {
        boolean b = this.updateById(resource);
        if (b){
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    /**
     * 分页查询资源列表
     * @param cur
     * @param size
     * @return
     */
    @Override
    public Result getResourceList(Integer cur, Integer size) {
        IPage<Resource> page = new Page<>(cur, size);
        IPage<Resource> resourcePage = resourceMapper.selectPage(page, null);
        List<Resource> records = resourcePage.getRecords();
        return Result.ok().data("data", records);
    }

    /**
     * 根据资源id查询对应的资源
     * @param id
     * @return
     */
    @Override
    public Result getResourceById(Integer id) {
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Resource resource = this.getOne(wrapper);
        return Result.ok().data("data", resource);
    }

    /**
     * 根据角色id查询其拥有的资源信息
     * @param rid
     * @return
     */
    @Override
    public List<Resource> getResourceListByRoleId(Integer rid) {
        return resourceMapper.getResourceByRoleId(rid);
    }

    /**
     * 查询所有的菜单，包括其对应需要的角色
     * @return
     */
    @Override
    public List<ResourceDTO> getResourcesWithRoles() {
        return resourceMapper.getResourcesWithRoles();
    }
}
